import { ref } from 'vue';
import { getAccessTypeEnumSchema } from '@/enums/accessTypeEnum';
import { AdColumn } from '@/components/AdTable';
import { useI18n } from '@/hooks/web/useI18n';

import { readModules } from '@/api/authorization/admin/module';

const accessTypeEnumSchema = getAccessTypeEnumSchema();

const { t } = useI18n();

export const searchInput = ref();

/** 模块信息树形结构 */
export interface ModuleTreeNode {
  /** 模块编号 */
  Id: string | bigint;

  /** 模块编码 */
  Code: string;
  /** 模块名称 */
  Name: string;

  /** 模块完整编码 */
  FullCode: string;
  /** 模块完整名称 */
  FullName: string;

  /** 备注 */
  Remark: string;

  /** 顺序编号 */
  OrderNumber: number;
  /** 节点树形路径 */
  TreePathString: string;
  /** 父模块编号 */
  ParentId?: string | bigint | null;

  /** 创建时间 */
  CreatedTime: Date;

  /** 层级 */
  Level?: number;
  /** 子集 */
  Children?: ModuleTreeNode[];
}

export const columns: AdColumn[] = [
  {
    title: t('entity.idTitle'),
    dataIndex: 'Id',
    width: 180,
    align: 'left',
    ifShow: false,
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.codeTitle'),
    dataIndex: 'Code',
    width: 250,
    align: 'left',
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.nameTitle'),
    dataIndex: 'Name',
    width: 150,
    align: 'left',
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.fullCodeTitle'),
    dataIndex: 'FullCode',
    width: 300,
    align: 'left',
    resizable: true,
    // customFilterDropdown: true,
    // onFilter: (value, record) => {
    //   const flag = deepQuery([record], value.toString(), 'FullCode');
    //   console.log('aa', { value, record, flag });
    //   return flag ? true : false;
    //   return record.FullCode.toString().toLowerCase().includes(value.toString().toLowerCase());
    // },
  },
  {
    title: t('routes.system.authorization.module.fullNameTitle'),
    dataIndex: 'FullName',
    width: 300,
    align: 'left',
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.remarkTitle'),
    dataIndex: 'Remark',
    width: 200,
    align: 'left',
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.orderNumberTitle'),
    dataIndex: 'OrderNumber',
    width: 75,
    align: 'right',
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.treePathStringTitle'),
    dataIndex: 'TreePathString',
    width: 300,
    align: 'left',
    ifShow: false,
    resizable: true,
  },
  {
    title: t('routes.system.authorization.module.parentIdTitle'),
    dataIndex: 'ParentId',
    width: 100,
    align: 'left',
    ifShow: false,
    resizable: true,
  },
  {
    title: t('entity.creationAudited.createdTimeTitle'),
    dataIndex: 'CreatedTime',
    width: 180,
    align: 'center',
    ifShow: false,
    resizable: true,
    dataType: 'datetime',
  },
];

export const moduleFunctionColumns: AdColumn[] = [
  {
    title: t('routes.system.authorization.functionIdTitle'),
    dataIndex: 'Id',
    width: 0,
    ifShow: false,
    defaultHidden: true,
    filterable: false,
    dataType: 'integer',
  },
  {
    title: t('routes.system.authorization.functionNameTitle'),
    dataIndex: 'Name',
    width: 300,
    filterable: true,
    dataType: 'string',
  },
  {
    title: t('routes.system.authorization.functionAccessTypeTitle'),
    dataIndex: 'AccessType',
    width: 100,
    filterable: true,
    dataType: 'enum',
    enumData: accessTypeEnumSchema,
  },
  {
    title: t('routes.system.authorization.functionAreaTitle'),
    dataIndex: 'Area',
    width: 150,
    filterable: true,
    dataType: 'string',
  },
  {
    title: t('routes.system.authorization.functionControllerTitle'),
    dataIndex: 'Controller',
    width: 200,
    filterable: true,
    dataType: 'string',
  },
];

export async function getModuleTreeNodes() {
  let moduleTreeNodes: ModuleTreeNode[] = [];

  const modules = await readModules();
  if (modules && modules.length > 0) {
    //拿到父级数组
    const parentModules = modules.filter((m) => !m.ParentId && m.ParentId?.toString() !== '0');
    //递归的方法
    const roBack = (parents: ModuleTreeNode[], children: ModuleTreeNode[]) => {
      parents.forEach((item) => {
        //设置层级
        item.Level = item.Level ? item.Level : 1;
        const en: ModuleTreeNode[] = [];
        children.forEach((ch) => {
          if (ch.ParentId && ch.ParentId === item.Id) {
            ch.Level = item.Level ? item.Level + 1 : 1;
            //给it添加children属性
            if (!item.Children) {
              item.Children = [];
            }
            item.Children?.push(ch);
            en.push(ch);
          }
        });
        //调用自身实现递归
        roBack(en, children);
      });
      moduleTreeNodes = parents;
    };
    //调用递归函数
    roBack(parentModules, modules);
  }

  // const lists = [
  //   { id: 3, title: '子级2', parentId: 1 },
  //   { id: 2, title: '子级1', parentId: 1 },
  //   { id: 1, title: '父级1' },
  //   { id: 4, title: '父级2' },
  //   { id: 5, title: '子级3', parentId: 4 },
  //   { id: 6, title: '子级4', parentId: 5 },
  // ];
  // //拿到父级数组
  // const list2 = lists.filter((it) => !it.parentId && it.parentId !== 0);
  // let res;
  // //递归的方法
  // const roback1 = (entity1: any, child: any) => {
  //   entity1.forEach((it) => {
  //     //给it添加children属性
  //     it.children = [];
  //     const en = [];
  //     child.forEach((ch) => {
  //       if (ch.parentId && ch.parentId === it.id) {
  //         it.children.push(ch);
  //         en.push(ch);
  //       }
  //     });
  //     //调用自身实现递归
  //     roback1(en, child);
  //   });
  //   res = entity1;
  // };
  // roback1(list2, lists);
  // console.log(res);

  return moduleTreeNodes;
}

/** 深度递归查找 */
export function deepQuery(tree: Recordable[], value: string, field: string): Recordable | null {
  let isGet = false;
  let retNode: Recordable | null = null;
  function deepSearch(tree: Recordable[], value: string, field: string) {
    for (let i = 0; i < tree.length; i++) {
      if (tree[i].Children && tree[i].Children.length > 0) {
        deepSearch(tree[i].Children, value, field);
      }
      if (value === tree[i][field] || isGet) {
        isGet || (retNode = tree[i]);
        isGet = true;
        break;
      }
    }
  }
  deepSearch(tree, value, field);
  return retNode;
}
